#include <iostream>
#include <atomic>
#include <memory>
#include <type_traits>
#include <utility>
using namespace std;

namespace myshared_ptr
{
    template<typename T>
    class shared_ptr {
    private:
        T* ptr;
        atomic<size_t>* ref_count;

        void release() {
            if (ref_count && ref_count->fetch_sub(1) == 1) {
                delete ptr;
                delete ref_count;
            }
        }

    public: // 修正：添加 public 访问修饰符
        shared_ptr() : ptr(nullptr), ref_count(nullptr) {}
        
        explicit shared_ptr(T* p) : ptr(p), ref_count(p ? new atomic<size_t>(1) : nullptr) {}
        
        shared_ptr(const shared_ptr<T>& other) : ptr(other.ptr), ref_count(other.ref_count) {
            if (ref_count) {
                ref_count->fetch_add(1);
            }
        }
        
        shared_ptr<T>& operator=(const shared_ptr<T>& other) { // 修正：参数加 const
            if (this != &other) {
                release();
                ptr = other.ptr;
                ref_count = other.ref_count;
                if (ref_count) {
                    ref_count->fetch_add(1);
                }
            }
            return *this;
        }
        
        shared_ptr(shared_ptr<T>&& other) noexcept : ptr(other.ptr), ref_count(other.ref_count) {
            other.ptr = nullptr;
            other.ref_count = nullptr;
        }
        
        shared_ptr<T>& operator=(shared_ptr<T>&& other) noexcept {
            if (this != &other) {
                release();
                ptr = other.ptr;
                ref_count = other.ref_count;
                other.ptr = nullptr;
                other.ref_count = nullptr;
            }
            return *this;
        }
        
        T& operator*() const {
            return *ptr;
        }
        
        T* operator->() const {
            return ptr;
        }
        
        size_t use_count() const {
            return ref_count ? ref_count->load() : 0;
        }
        
        T* get() const {
            return ptr;
        }
        
        // 重置函数，参数为指针p，默认为nullptr
        void reset(T* p = nullptr) {
            // 释放指针
            release();
            // 将指针ptr指向p
            ptr = p;
            // 如果p不为空，则创建一个新的atomic<size_t>对象，并将ref_count指向该对象
            ref_count = p ? new atomic<size_t>(1) : nullptr;
        }
        
        ~shared_ptr() {
            release();
        }
    }; // 修正：类定义结尾添加分号
} // 修正：闭合命名空间
class MyClass {
public:
    int value;
    MyClass(int v) : value(v) {}
    // 打印MyClass的值
    void print() const {
        cout << "MyClass value: " << value << endl;
    }
};
    
int main(){


    myshared_ptr::shared_ptr<MyClass> p4(new MyClass(10));
    cout<<p4->value<<endl;
    cout<<(*p4).value<<endl;
    return 0;
}